package com.budweiser.user.controller;

import com.budweiser.commons.utils.Utils;
import com.budweiser.model.log.LogAnnotation;
import com.budweiser.model.page.Page;
import com.budweiser.model.result.ResponseBase;
import com.budweiser.model.result.ResultBase;
import com.budweiser.model.user.Permission;
import com.budweiser.model.user.Role;
import com.budweiser.user.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/role")
public class RoleController {
	@Autowired
	private RoleService roleService;

	@GetMapping("/all")
	public Page<Role> findRoles(Map<String, Object> params, String limit, String page) {
		params.put("start", page);
		params.put("length", limit);
		return roleService.findRoles(params);
	}

	@LogAnnotation(module = "新增角色")
	@PostMapping("/save")
	@PreAuthorize("hasAuthority('back:role:save')")
	public ResponseBase save(Role role) {
		roleService.save(role);
		return new ResponseBase(200, "新增成功！", null);
	}

	@LogAnnotation(module = "修改角色")
	@PostMapping("/update")
	@PreAuthorize("hasAuthority('back:role:update')")
	public ResponseBase update(Role role) {
		roleService.update(role);
		return new ResponseBase(200, "修改成功！", null);
	}

	@LogAnnotation(module = "删除角色")
	@PostMapping("/del")
	@PreAuthorize("hasAuthority('back:role:delete')")
	public ResponseBase del(String ids) {
		roleService.deleteRole(Utils.getLongs(ids));
		return new ResponseBase(200, "删除成功！", null);
	}

	/***
	 * 根据角色Id查询权限
	 * @param roleid
	 * @return
	 */
	@GetMapping("/findPermissionByroleid")
	public ResultBase<Permission> getPermissionList(Long roleid) {
		return new ResultBase<Permission>(0, "数据加载成功！", 0, roleService.getPermissionList(roleid));
	}
	/**
	 * 管理后台给角色分配权限
	 *
	 * @param            角色id
	 * @param permissionIds 权限ids
	 */
	@LogAnnotation(module = "分配权限")
	@PreAuthorize("hasAuthority('back:role:permission:set')")
	@PostMapping("/setPermissionToRole")
	public ResponseBase setPermissionToRole(Long roleid, String permissionIds) {
		roleService.setPermissionToRole(roleid, Utils.getLongs(permissionIds));
		return new ResponseBase(200, "分配权限成功！", null);
	}
}
